package cloud.maque.module.system.service.impl;

import cloud.maque.common.core.exceptions.BusinessException;
import cloud.maque.common.core.utils.TokenUserUtil;
import cloud.maque.module.system.entity.SysMenu;
import cloud.maque.module.system.mapper.MenuMapper;
import cloud.maque.module.system.service.MenuPrivilegeService;
import cloud.maque.module.system.service.MenuService;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import java.util.Date;
import java.util.List;

@Service
public class MenuServiceImpl extends ServiceImpl<MenuMapper, SysMenu> implements MenuService {

    @Autowired
    TokenUserUtil userUtil;


    @Autowired
    MenuPrivilegeService menuPrivilegeService;

    @Override
    public List<SysMenu> GetList(SysMenu data) {
        QueryWrapper<SysMenu> query = new QueryWrapper<>();
        query.lambda().eq(SysMenu::getMenuName, data.getMenuName());
        query.lambda().orderByAsc(SysMenu::getOrderNum);
        return this.list(query);
    }

    @Override
    @Transactional
    public SysMenu SaveMenu(SysMenu data) {
        Assert.hasText(data.getMenuName(), "菜单名称不能为空");
        Assert.hasText(data.getMenuType(), "菜单类型不能为空");


        if (StrUtil.isEmptyIfStr(data.getMenuId())) {
            data.setCreateBy(userUtil.GetUserName());
            data.setCreateTime(new Date());
            data.setUpdateBy(data.getCreateBy());
            data.setUpdateTime(new Date());
        } else {
            SysMenu oldPost = this.baseMapper.selectById(data.getMenuId());
            if (oldPost != null) {
                data.setCreateTime(oldPost.getCreateTime());
                data.setCreateBy(oldPost.getCreateBy());
            }
            data.setUpdateBy(userUtil.GetUserName());
            data.setUpdateTime(new Date());

        }

        if (!StrUtil.isEmpty(data.getPerms())) {
            SysMenu oldPost = GetByPerms(data.getPerms());
            if (oldPost != null && !oldPost.getMenuId().equals(data.getMenuId())) {
                throw new BusinessException("权限编码已存在");
            }
        }

        this.saveOrUpdate(data);

        //插入权限
        menuPrivilegeService.SavePrivilege(data.getMenuId());

        return data;
    }

    private SysMenu GetByPerms(String code) {

        QueryWrapper<SysMenu> query = new QueryWrapper<>();
        query.lambda().eq(SysMenu::getPerms, code);
        return this.getOne(query, false);
    }

    @Override
    public Boolean DeleteMenu(String menuId) {
        return this.removeById(menuId);
    }
}
